#include "myservergateway.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include "mydata.h"
#include "mysql.h"

MyServerGateway *MyServerGateway::obj = nullptr;

MyServerGateway *MyServerGateway::getObject()
{
    if(obj == nullptr)
        obj = new MyServerGateway;
    return obj;
}
//网关
void MyServerGateway::handleFrame(const QByteArray &data, int src)
{
    qDebug() << "Gateway" << data;
    QJsonObject jsonData = QJsonDocument::fromJson(data).object();
    if(!jsonData.contains("index"))
        return;
    int index = jsonData.value("index").toInt();
    if(index == 2001)
    {
        //传感协议
        int co2 = jsonData.value("co2").toInt();
        //烟雾
        bool smoke = jsonData.value("smoke").toBool();
        int pm2_5 = jsonData.value("pm2_5").toInt();
        //光照
        int illumination = jsonData.value("illumination").toInt();
        //人体红外
        bool inf1 = jsonData.value("inf1").toBool();
        bool inf2 = jsonData.value("inf2").toBool();
        //甲烷
        bool methane = jsonData.value("methane").toBool();
        //紫外线
        int ultraviolet_rays = jsonData.value("ultraviolet_rays").toInt();
        bool fire = jsonData.value("fire").toBool();
        //对射
        bool antiphoto = jsonData.value("antiphoto").toBool();
        //反射
        bool reflection = jsonData.value("reflection").toBool();
        double temperature = jsonData.value("temperature").toDouble();
        double humidity = jsonData.value("humidity").toDouble();
        //存--》数据模块
        MyData::getObject()->co2 = co2;
        MyData::getObject()->smoke = smoke;
        MyData::getObject()->pm2_5 = pm2_5;
        MyData::getObject()->illumination = illumination;
        MyData::getObject()->inf1 = inf1;
        MyData::getObject()->inf2 = inf2;
        MyData::getObject()->methane = methane;
        MyData::getObject()->ultraviolet_rays = ultraviolet_rays;
        MyData::getObject()->fire = fire;
        MyData::getObject()->antiphoto = antiphoto;
        MyData::getObject()->reflection = reflection;
        MyData::getObject()->temperature = temperature;
        MyData::getObject()->humidity = humidity;
        //存--》数据库
        MySql::getObject()->saveData(
            co2, smoke, pm2_5, illumination, inf1,
            inf2, methane, ultraviolet_rays, fire,
            antiphoto, reflection, temperature, humidity
                    );
    }
}

void MyServerGateway::setHighlightLED(int brightness)
{
    QJsonObject jsonData;
    jsonData.insert("index", 1001);
    jsonData.insert("brightness", brightness);
    QByteArray data = QJsonDocument(jsonData).toJson();
    sendDataToAllClient(data);
}














